from django.db import models
from django.urls import reverse

from datetime import datetime

# Create your models here.


class Category(models.Model):
    name = models.CharField(max_length=30, verbose_name='分类名')
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')

    class Meta:
        verbose_name = '分类'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class Tag(models.Model):
    name = models.CharField(max_length=30, verbose_name='标签名')
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')

    class Meta:
        verbose_name = '标签'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class Article(models.Model):
    title = models.CharField(max_length=30, verbose_name='标题')
    author = models.CharField(max_length=30, verbose_name='作者')
    summary = models.CharField(max_length=250, verbose_name='摘要')
    content = models.TextField(verbose_name='内容')
    category = models.ForeignKey(Category, verbose_name='分类')
    tag = models.ManyToManyField(Tag, verbose_name='标签')
    view_nums = models.IntegerField(default=0, verbose_name='浏览数')
    # comment_nums = models.IntegerField(default=0, verbose_name='评论数')
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')

    class Meta:
        ordering = ['-add_time']    # ordering定义排序, 此处表示文章按创建时间降序排列
        verbose_name = '文章'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('detail', kwargs={'article_id': self.id})

    # 文章阅读量
    def increase_views(self):
        self.view_nums += 1
        self.save(update_fields=['view_nums'])

